package com.globallogic.socialnetwork.service;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.InitialContext;

import org.apache.log4j.Logger;

@Resource(mappedName = "jms/Queue-0")
public class MessageConn {

	@Resource(mappedName = "jms/ConnectionFactory-0")
	private ConnectionFactory connectionFactory;

	@Resource(mappedName = "jms/Queue-0")
	private Queue queue;

	Connection connection = null;
	Session session = null;
	MessageProducer producer = null;
	private final static Logger log = Logger
			.getLogger("SocialNetworkFileLogger");

	public MessageConn(String sender, String receiver, String messageText) {
		try {
			log.warn("MessageConn()");
			InitialContext ctx = new InitialContext();
			connectionFactory = (ConnectionFactory) ctx
					.lookup("jms/ConnectionFactory-0");
			queue = (Queue) ctx.lookup("jms/Queue-0");
			connection = connectionFactory.createConnection();
			session = connection.createSession(false,
					QueueSession.AUTO_ACKNOWLEDGE);
			producer = session.createProducer(queue);
			MapMessage message = session.createMapMessage();
			message.setString("sender", sender);
			message.setString("receiver", receiver);
			message.setString("message", messageText);
			producer.send(message);

			session.close();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
	}

	public MessageConn() {

	}
}